#!/usr/bin/env python
#
# Copyright 2008 Takashi Matsuo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

try:
  from django import newforms as forms
  from django.newforms.util import flatatt, StrAndUnicode, smart_unicode
except ImportError:
  from django.forms.util import flatatt, StrAndUnicode, smart_unicode
  from django import forms

try:
  from django.utils.translation import ugettext_lazy as _
except ImportError:
  pass

from google.appengine.ext import db
from google.appengine.ext.db.djangoforms import monkey_patch

class GeoPtInput(forms.TextInput):
  width = 300
  height = 300
  zoomlevel = 14
  lat = -25.34808
  lng = -49.237976
  def render(self, name, value, attrs=None):
    if value is None: value = ''
    final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
    if value != '':
      # Only add the 'value' attribute if a value is non-empty.
      try:
        final_attrs['value'] = smart_unicode(value)
        isset = "true"
        (lat, lng) = [float(val) for val in final_attrs['value'].split(',')]
      except ValueError:
        pass
    else:
      (lat, lng, isset) = (self.lat, self.lng, "false")
    input_field = u"""<input%(inputs)s />
    <input type='button' onClick='javascript:gmap_open_%(id)s();'
      value='%(open)s'/>
    <input type='button' onClick='javascript:gmap_close_%(id)s();'
      value='%(close)s'/>
    """ % {'inputs': flatatt(final_attrs),
           "id": final_attrs['id'],
           "open": "Open Map",
           "close": "Close Map",
           }
    javascripts = u"""
    <script type="text/javascript">
    //<![CDATA[
    function gmap_close_%(id)s() {
      var elm = document.getElementById('div_%(id)s');
      if (elm) {
        document.body.removeChild(elm);
      }
    }
    function gmap_open_%(id)s() {
      if (! document.getElementById('div_%(id)s')) {
        var map_div = document.createElement('DIV');
        map_div.id = 'div_%(id)s';
        map_div.style.width= '%(width)dpx'
        map_div.style.height= '%(height)dpx'
        document.body.appendChild(map_div);
      }
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById('div_%(id)s'));
        map.setCenter(new GLatLng(%(lat)f,%(lng)f), %(zoomlevel)d);
        GEvent.addListener(map, 'click', function(overlay, point) {
          var form_value = point.toUrlValue();
          document.getElementById('%(id)s').value=form_value;
          var latLngStr = 'lat, lng = ' + form_value;
          map.openInfoWindow(point, latLngStr);
        });
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        var lsc = new google.maps.LocalSearch();
        map.addControl(new google.maps.LocalSearch());
        map.enableScrollWheelZoom();
        if (%(isset)s) {
          var point = new GLatLng(%(lat)f,%(lng)f);
          var latLngStr = 'lat, lng = ' + point.toUrlValue();
          map.openInfoWindow(point, latLngStr);
        }
      }
    }
    </script>
    """ % {'id': final_attrs['id'],
           'width': self.width,
           'height': self.height,
           'zoomlevel': self.zoomlevel,
           'lat': self.lat,
           'lng': self.lng,
           'isset': isset,
           }
    return input_field + javascripts

class GeoPtField(forms.Field):
  widget = GeoPtInput
  
class GeoPtProperty(db.GeoPtProperty):
  __metaclass__ = monkey_patch

  def get_form_field(self, **kwargs):
    defaults = {'form_class': GeoPtField}
    defaults.update(kwargs)
    return super(GeoPtProperty, self).get_form_field(**defaults)
